//
//  LoginViewController.m
//  TripPlatformTest
//
//  Created by 陈曦 on 16/1/6.
//  Copyright © 2016年 chenxi. All rights reserved.
//

#import "LoginViewController.h"
#import "Define.h"
#import "RegisterViewController.h"
#import "RetrievePasswordViewController.h"
#import "Userinfo.h"
#import "MainPageViewController.h"
#import "AFNetworking.h"
#import "NetRequestGroup.h"
#import "Access_token.h"
#import "MBProgressHUD.h"


@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = NO;
    
    //定义视图背景色
    self.view.backgroundColor = [UIColor colorWithRed:240 / 255.0 green:240 / 255.0 blue:240 / 255.0 alpha:1];
    
    //导航条名字
    //    self.navigationItem.title = @"快速注册";
    //    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor] , NSFontAttributeName : [UIFont boldSystemFontOfSize:18]};
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = @"登录";
    self.navigationItem.titleView = titleLabel;
    
    //重定义返回键
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(0, 0, 22, 22);
    [back setImage:[UIImage imageNamed:@"iconfont-fanhui-white"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backTpMainView) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backBar = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backBar;
    
    [self inputTextField];
    
    

}
//==============================================================================

#pragma mark 输入框搭建
-(void)inputTextField{
    
    CGFloat inputSpaceValue = kScreenHeightEight * 0.7;
    
    UIView *inputView = [[UIView alloc] initWithFrame:CGRectMake(-0.5, kScreenHeightEight, kScreenWidth + 1, inputSpaceValue * 2)];
    inputView.layer.borderColor = [UIColor colorWithRed:215 / 255.0 green:215 / 255.0 blue:215 / 255.0 alpha:1].CGColor;
    inputView.layer.borderWidth = 0.5;
    inputView.layer.masksToBounds = YES;
    inputView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:inputView];
    
    //中间间隔线
    UILabel *septaLine = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidthTen / 2, kScreenHeightEight * 0.7, kScreenWidth - kScreenWidthTen / 2, 0.5)];
    septaLine.backgroundColor = lineColor;
    [inputView addSubview:septaLine];
    
    UIImageView *phoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidthTen / 2, inputSpaceValue / 4, inputSpaceValue / 2 * 0.92 / 1.55, inputSpaceValue / 2)];
    phoneImageView.image = [UIImage imageNamed:@"iconfont-shouji"];
    [inputView addSubview:phoneImageView];
    
    UIImageView *passwordImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidthTen / 2, inputSpaceValue / 4 + inputSpaceValue, inputSpaceValue / 2 * 1.23 / 1.55, inputSpaceValue / 2)];
    passwordImageView.image = [UIImage imageNamed:@"iconfont-password"];
    [inputView addSubview:passwordImageView];
    
    //手机号注册框
    self.phoneNumberLoginTextField = [[UITextField alloc] initWithFrame:CGRectMake(kScreenWidthTen * 1.5, inputSpaceValue / 4, kScreenWidth / 2, inputSpaceValue / 2)];
    self.phoneNumberLoginTextField.delegate = self;
    self.phoneNumberLoginTextField.placeholder = @"请输入手机号";
    self.phoneNumberLoginTextField.textAlignment = NSTextAlignmentLeft;
    self.phoneNumberLoginTextField.keyboardType = UIKeyboardTypeNumberPad;
    [inputView addSubview:self.phoneNumberLoginTextField];
    
    //密码输入框
    self.passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(kScreenWidthTen * 1.5, inputSpaceValue / 4 + inputSpaceValue, kScreenWidth / 2, inputSpaceValue / 2)];
    self.passwordTextField.placeholder = @"请输入密码";
    self.passwordTextField.secureTextEntry = YES;//密文模式
    self.passwordTextField.textAlignment = NSTextAlignmentLeft;
    [inputView addSubview:self.passwordTextField];
    
    
    //登录按钮
    self.LoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.LoginBtn.frame = CGRectMake(kScreenWidthTen / 2, kScreenHeightEight * 3, kScreenWidth - kScreenWidthTen, kScreenHeightEight / 2);
    self.LoginBtn.backgroundColor = mainColor;
    self.LoginBtn.layer.cornerRadius = 5;
    [self.LoginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.LoginBtn addTarget:self action:@selector(LoginPush) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.LoginBtn];
    
    //快速注册
    UIButton *quickRegisterBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    quickRegisterBtn.backgroundColor = [UIColor clearColor];
    quickRegisterBtn.frame = CGRectMake(kScreenWidthTen / 2, kScreenHeightEight * 3.8, kScreenWidthEight * 1.5, kScreenHeightTen / 3.5);
    [quickRegisterBtn setTitle:@"快速注册" forState:UIControlStateNormal];
    quickRegisterBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [quickRegisterBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [quickRegisterBtn addTarget:self action:@selector(quickRegisterPush) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:quickRegisterBtn];
    
    //找回密码
    UIButton *findPasswordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    findPasswordBtn.backgroundColor = [UIColor clearColor];
    findPasswordBtn.frame = CGRectMake(kScreenWidthEight * 6.2, kScreenHeightEight * 3.8, kScreenWidthEight * 1.5, kScreenHeightTen / 3.5);
    [findPasswordBtn setTitle:@"找回密码" forState:UIControlStateNormal];
    findPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [findPasswordBtn setTitleColor:[UIColor colorWithRed:0 / 255.0 green:137 / 255.0 blue:225 / 255.0 alpha:1] forState:UIControlStateNormal];
    [findPasswordBtn addTarget:self action:@selector(findPassWordPush) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:findPasswordBtn];
    
    
    //创建一个轻拍手势 回收键盘
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    
    [self.view addGestureRecognizer:tap];
    
    
}
//==============================================================================

#pragma mark 跳转向注册界面
- (void) quickRegisterPush{
    
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];

    [self.navigationController pushViewController:registerVC animated:nil];


}
//==============================================================================

#pragma mark 跳转向找回密码界面
- (void) findPassWordPush{

    RetrievePasswordViewController *retrievePasswordVC = [[RetrievePasswordViewController alloc] init];
    [self.navigationController pushViewController:retrievePasswordVC animated:nil];

}

//==============================================================================

#pragma mark 登录后跳转
- (void)LoginPush{
    //网络解析后跳转
    [self NetworkRequests];
}

//==============================================================================
#pragma mark 网络请求
- (void) NetworkRequests{
    
    //初始化进度框，置于当前的View当中
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.label.text = @"正在加载";
    [HUD showAnimated:YES];//HUD开始
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    //传入的参数
    NSDictionary *para = @{
                           @"type" : @"1",
                           @"mobile" : self.phoneNumberLoginTextField.text,
                           @"password" : self.passwordTextField.text
                           };

    //你的接口地址
    NSString *url = [NSString stringWithFormat:@"%@%@", kRealmName,kNetworkInterfaceLogin];
    //发送请求
    [manager POST:url parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [HUD hideAnimated:YES];

        self.loginParameterModel = [[LoginParameterModel alloc] init];
        
        NSDictionary *dic = responseObject;
        
        self.loginParameterModel.status = dic[@"status"];
                
        self.loginParameterModel.msg = dic[@"msg"];
        
        NSDictionary *infoDic = dic[@"info"];
        
        self.loginParameterModel.access_token = infoDic[@"access_token"];
        
        self.access_token = infoDic[@"access_token"];
        
        Access_token *useAccess = [Access_token shareInstance];
        useAccess.access_token = self.access_token ;
        
        
        //返回值分析
        [self resultAnalysis];


    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [HUD hideAnimated:YES];
        
        //初始化提示框；
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有网络" preferredStyle:  UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //点击按钮的响应事件；
        }]];
        
        //弹出提示框；
        [self presentViewController:alert animated:true completion:nil];
        
    }];
    
}
//==============================================================================
#pragma mark 返回值分析
- (void) resultAnalysis {
    
    int status = [self.loginParameterModel.status intValue];
    
    switch (status) {
        case 99:{
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.loginParameterModel.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
            }
            
            break;
        case 98:{
            
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.loginParameterModel.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
        case 97:
                {
                //初始化提示框；
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.loginParameterModel.msg preferredStyle:  UIAlertControllerStyleAlert];
                
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //点击按钮的响应事件；
                }]];
                
                //弹出提示框；
                [self presentViewController:alert animated:true completion:nil];
                
            }
            
            break;
        case 96:
        {
            
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.loginParameterModel.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            
            break;
        case 1:
        {
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.loginParameterModel.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
        case 2:
        {
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.loginParameterModel.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
        case 3:
        {
            //初始化提示框；
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.loginParameterModel.msg preferredStyle:  UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                //点击按钮的响应事件；

            }]];
            
            //弹出提示框；
            [self presentViewController:alert animated:true completion:nil];

            
        }
            break;
        case 100:
        {
            
//            //初始化提示框；
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:self.loginParameterModel.msg preferredStyle:  UIAlertControllerStyleAlert];
            
//            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //点击按钮的响应事件；
                //回收键盘
                [self.view endEditing:YES];
                
                //登录单例
                Userinfo *user = [Userinfo shareInstance];
                user.isLogin = YES;
                
                //判断block是否有值,如果有,不为空,才会执行block,否则什么都不执行
                if(_successBlock != nil){
                    _successBlock();//执行block,跳转到下一界面
                } else {
                
                MainPageViewController *mainVC = [[MainPageViewController alloc] init];
                    
                [self.navigationController pushViewController:mainVC animated:nil];
                
                }
//            }]];
            
            //弹出提示框；
//            [self presentViewController:alert animated:true completion:nil];
            
        }
            break;
            
        default:
            break;
    }
    
    
    
}



//==============================================================================

#pragma mark 键盘只能输入数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [self validateNumber:string];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}
//=============================================================================

//结束编辑,点击空白回收键盘
- (void)tap
{
    
    //回收键盘
    [self.view endEditing:YES];
    
}
//==============================================================================

//返回主页
- (void)backTpMainView{
    
    //回收键盘
    [self.view endEditing:YES];
    
    MainPageViewController *mainVC = [[MainPageViewController alloc] init];
    
    [self.navigationController pushViewController:mainVC animated:nil];

}

@end
